#!/usr/bin/python -d
#-*- coding:utf-8 -*-

import ldap, ldap.modlist
import logging
from repr import repr



class LDAP_Worker:
    
    def __init__(self, server, user_id):
        self.__server = server
        self.user_id = user_id
        base = self.__get_base()
        logging.debug( "el BaseDN del servidor es:%s" %(base))
        if len(base) == 0:
            logging.error('imposible configurar baseDN de LDAP')
            return
        self.baseDN = "uid=%s,ou=People,%s" % (self.user_id, base)
        
        logging.debug("el BaseDN es: %s" %(self.baseDN))
        self.ldap_conn = ldap.initialize('ldap://%s' %self.__server)
        try:
            result_int = self.ldap_conn.simple_bind('cn=admin,'+base,
                                                     'Ynv71L3z')
        except ldap.INVALID_CREDENTIALS as invalid_cred_exc:
            logging.error("credenciales de administracion para ldap incorrectas")
            return
        except Exception as e:
            logging.error("imposible loguear contra ldap: %s" %repr(e))
            return
        else:
            logging.debug("logueo con ldap://%s correcto" %(self.__server))
        
    def __get_base(self):
        ldap_conf = open('/etc/ldap/ldap.conf').readlines()
        if len(ldap_conf) > 0:
            ldap_conf.reverse()
            for line in ldap_conf:
                if line.startswith("BASE"):
                    return line.replace("BASE", "").strip()
        return ''
    
    def get_homeDirectory(self):
        
        search_result = self.ldap_conn.search_s( self.baseDN,  
                                                 ldap.SCOPE_SUBTREE,
                                                 '(uid=%s)' %self.user_id,
                                                 ['homeDirectory'])
        for result in search_result:
            return result[1].get('homeDirectory')[0]
    
    
    def is_movil(self):
        if self.get_homeDirectory().startswith('/home/nfs/'):
            return True
        else:
            return False
    
    def migrate_to_fijo(self):
        
        homeDirectory = self.get_homeDirectory()
        
        homeDirectory_movil = {'homeDirectory':'/home/nfs/%s' %self.user_id}
        homeDirectory_fijo = {'homeDirectory':'/home/%s' %self.user_id}
        
        if homeDirectory == homeDirectory_fijo:
            logging.info("usuario %s ya migrado %s" 
                         %( self.user_id, homeDirectory))
            return
        else:
            #creamos le cambio
            changes_list = ldap.modlist.modifyModlist(homeDirectory_movil,
                                                      homeDirectory_fijo)
            
            #buscamos personas y aplicamos el cambio
            search_result = self.ldap_conn.search_s(self.baseDN,
                                                    ldap.SCOPE_SUBTREE,
                                                    '(uid=%s)' %self.user_id,
                                                    ['homeDirectory'])
            user_result = search_result[0][0]
            for person in search_result:
                if person is None: 
                    logging.debug("resultado vacío")
                try:
                    self.ldap_conn.modify_s(person[0],changes_list)
                except Exception as e:
                    logging.error("imposible llevar a cabo: %s" %repr(e))
                    
    def migrate_to_movil(self):
        homeDirectory_movil = {'homeDirectory':'/home/nfs/%s' %self.user_id}
        homeDirectory_fijo = {'homeDirectory':'/home/%s' %self.user_id}
        changes_list = ldap.modlist.modifyModlist(homeDirectory_fijo,
                                                  homeDirectory_movil)
        search_result = self.ldap_conn.search_s( self.baseDN,
                                                 ldap.SCOPE_SUBTREE,
                                                 '(uid=%s)' %self.user_id,
                                                 ['homeDirectory'])
        for person in search_result:
            try:
                self.ldap_conn.modify_s(person[0],changes_list)
            except Exception as e:
                logging.error("imposible llevar a cabo: %s" %repr(e))
        
if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s %(filename)s:%(lineno)d %(funcName)s - %(levelname)s: %(message)s")
    
    for server in ['c0', 'f0']:
        logging.debug("ola k ase, probando con servidor LDAP: %s" %server)
        try:
            user = 'ssm'
            ldap_w = LDAP_Worker(server=server, user_id=user)
            logging.debug('el homeDirectory de %s es %s' %(user,ldap_w.get_homeDirectory()))
            ldap_w.migrate_to_fijo()
            logging.debug("se migra a fijo, homeDierctory: %s" %(ldap_w.get_homeDirectory()))
            home_dir = ldap_w.get_homeDirectory()
            if (home_dir.startswith('/home/'+user)):
                ldap_w.migrate_to_movil()
                logging.debug("revirtiendo los cambios, se deja homeDirectory: %s" %(ldap_w.get_homeDirectory()))
            
        except Exception as e:
            logging.error("excepcion: %s" %(repr(e)))
        
        
        
        
        